var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');

var app = getApp();

Page({
  data: {
    isOpenShop: false,  //检测当前微信用户是否已经开店
    applyStatus: 1, //0表示无申请，1表示已提交申请但未通过，2表示申请已通过
    vendorShop: {}, //供应商店铺名称
    applyAgentShop: {}, //申请的代理商
    applyAgentUser: {} //申请代理商的用户
  },
  applyAgent: function () {
    let that = this;
    util.request(api.ApplyAgent, { vendorRootDeptId: that.data.vendorShop.deptId, agentRootDeptId: that.data.applyAgentShop.root_dept_id, applyAgentUserGrade: app.globalData.currentUserGrade })
      .then(function (res) {
        if (res.errno === 0) {
          wx.showToast({
            title: '已提交申请！',
            mask: true,
            success: function () {
              setTimeout(function() {
                wx.switchTab({
                  url: "/pages/index/index"
                })
              }, 2000)
            }
          })
        }
        else{
          wx.showToast({
            title: res.errmsg,
            mask: true,
            image: '/static/images/icon_error.png',
            success: function(){
              setTimeout(function () {
                wx.switchTab({
                  url: "/pages/index/index"
                })
              }, 2000)
            }
          })
        }
      }
    )
  },
  returnTo: function () {
    wx.switchTab({
      url: "/pages/index/index"
    })
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "代理申请"
    });

    let that = this;

    //获取当前微信用户信息
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      applyAgentUser: userInfo,
    })

    //检测当前微信用户是否已经开店
    util.request(api.QueryOpenShop).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          isOpenShop: true,
          applyAgentShop: res.data
        })

        //获取当前微信用户店铺详情
        var currentShop = wx.getStorageSync('currentShop');
        var currentRootDeptId = currentShop.rootDeptId;
        util.request(api.GetShopDetail, { deptId: currentRootDeptId })
          .then(function (res) {
            if (res.errno === 0) {
              that.setData({
                vendorShop: res.data.shopDetail
              });

              //检测是否存在代理申请记录
              util.request(api.CheckAgentApplyStatus, { vendorRootDeptId: that.data.vendorShop.deptId, agentRootDeptId: that.data.applyAgentShop.root_dept_id })
                .then(function (res) {
                  if (res.errno === 0) {
                    that.setData({
                      applyStatus: res.data
                    });
                  }
                }
              )
            }
          }
        )


      }
      else {
        that.setData({
          isOpenShop: false
        })
      }
    })
  },
  onShow: function () {
  }
})